import { Injectable, OnInit } from "@angular/core";
import { Http, Headers } from '@angular/http';

import { Hero } from "./hero";
import { HEROES } from "./hero.mock"

import 'rxjs/add/operator/toPromise';

@Injectable()
export class HeroService implements OnInit {

    private timestamp: number = 0;
    public heroes: Hero[] = [];


    private heroUrl = "http://localhost:3000/heroes/";
    private headers = new Headers({'Content-Type': 'application/json'});

    constructor(private http:Http){}

    handleError(err: any): Promise<any> {
        console.log("err occurs: ", err);
        return Promise.reject(err.message || err);
    }

    // getHeroes(): Hero[]{
    //     return HEROES;
    // }

    // getHeroesAsync(): Promise<Hero[]> {
    //     return Promise.resolve(HEROES);
    // }

    ngOnInit() {
        this.getHeroes();
    }

    getHero(id: number): Promise<Hero> {
        let hero: Hero;
        return this.getHeroes().then(heroes => {
            heroes.forEach(v => {
                if (v.id == id) hero = v;
            });
            return hero;
        }).catch(this.handleError);
    }

    getHeroes(): Promise<Hero[]> {
        console.log(this.heroes, this.timestamp);
        if (this.heroes.length == 0 || this.timestamp == 0 || (new Date()).valueOf() - this.timestamp > 30 * 1e3) {
            return this.http.get(this.heroUrl)
            .toPromise().then(res => {
                this.heroes = res.json() as Hero[];
                this.timestamp = (new Date()).valueOf();
                console.log("ready to get new data from server");
                return this.heroes;
            }).catch(this.handleError);
        } else {
            return Promise.resolve(this.heroes);
        }
    }

    addHero(name: string): Promise<Hero> {
        this.timestamp = 0;
        return this.http.post(`${this.heroUrl}/addHero`, JSON.stringify({"name":name}), {headers: this.headers})
        .toPromise().then(res => res.json()).catch(this.handleError);
    }

    updateHero(hero: Hero): Promise<Hero> {
        this.timestamp = 0;
        return this.http.post(`${this.heroUrl}/updateHero`, JSON.stringify({"id": hero.id,"name":hero.name}), {headers: this.headers})
        .toPromise().then(res => res.json()).catch(this.handleError);
    }

    removeHero(id: number): Promise<void> {
        this.timestamp = 0;
        return this.http.post(`${this.heroUrl}/updateHero`, JSON.stringify({"id": id}), {headers: this.headers})
        .toPromise().then(()=>null).catch(this.handleError);
    }
}
